//
//  ATIconDownloader.m
//  ATNetworks
//
//  Created by Ranjit2 on 16/05/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "ATIconDownloader.h"

#import "ATConnection.h"
#import "Reachability.h"

@interface ATIconDownloader (PRIVATE)

Reachability* hostReach;
Reachability* internetReach;
Reachability* wifiReach;
NSInteger connectionTag;
+ (NSMutableArray*)connectionsArray;
+ (NSMutableArray*)dataArray;
+ (NSMutableArray*)callBackTargetArray;

- (void) closeConnection:(ATConnection *)connection ;
- (void) updateInterfaceWithReachability: (Reachability*) curReach;
@end


static NSMutableArray *__callBackTargetArray;
static NSMutableArray *__connectionsArray;
static NSMutableArray *__dataArray;
static NSMutableArray *__indexArray;

@implementation ATIconDownloader

@synthesize id_;
@synthesize imageUrl;


+ (NSMutableArray*)callBackTargetArray {
	@synchronized(self) {
		if(!__callBackTargetArray) {
			__callBackTargetArray = [[NSMutableArray alloc] init];	
		}
	}
	
	return __callBackTargetArray;
} 

+ (NSMutableArray*)connectionsArray {
	@synchronized(self) {
		if(!__connectionsArray) {
			__connectionsArray = [[NSMutableArray alloc] init];	
		}
	}
	
	return __connectionsArray;
} 

+ (NSMutableArray*)dataArray {
	@synchronized(self) {
		if(!__dataArray) {
			__dataArray = [[NSMutableArray alloc] init];	
		}
	}
	
	return __dataArray;
} 

+ (NSMutableArray*)indexArray {
	@synchronized(self) {
		if(!__indexArray) {
			__indexArray = [[NSMutableArray alloc] init];	
		}
	}
	
	return __indexArray;
} 


- (void) openConnection : (NSString *)urlString withCallBackTarget:(NSIndexPath*)target_ withDelegate:(id)delegate_
{
//	NSLog(@"start openConnection");
	NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: urlString]];
	ATConnection *connection = [[ATConnection alloc] initWithRequest:request delegate:self startImmediately:YES withTag:[NSString stringWithFormat:@"%d", connectionTag]];
	connectionTag++;
	NSMutableData *_data = [NSMutableData dataWithLength:0];
	
	[[[self class] connectionsArray] addObject:connection];
	[[[self class] dataArray] addObject:_data];
	[[[self class] indexArray] addObject:target_];
	[[[self class] callBackTargetArray] addObject:delegate_];
	
//	NSLog(@"stop");
}

- (void) closeConnection:(ATConnection *)connection 
{
	if(connection == nil){
		
		for (int index = 0; index < [[[self class] callBackTargetArray] count]; index++) {
			id target = [[[self class] callBackTargetArray] objectAtIndex:index];
			
			
			
			NSMutableData *data = [[[self class] dataArray] objectAtIndex:index];
			UIImage *image = [UIImage imageWithData:data];
			[target imageDownloadFinish:image withId:[[[self class] indexArray] objectAtIndex:index]];
			
//			if([target respondsToSelector:selector]) {
//				[target performSelector:selector withObject:data];
//			}
		}
		
		
		[[[self class] callBackTargetArray] removeAllObjects];
		[[[self class] dataArray] removeAllObjects];
		[[[self class] connectionsArray] removeAllObjects];
		
	}
	else {
		//		NSLog(@"start closeConnection");
		//		NSLog(@"%@",connection);
		//		NSLog(@"%@",connection.tag);
		NSInteger index = [[[self class] connectionsArray] indexOfObject:connection];
		[[[self class] connectionsArray] removeObject:connection];
		
		id target = [[[self class] callBackTargetArray] objectAtIndex:index];
		

		NSLog(@"%@",[[self class] indexArray]);
		NSLog(@"%@",[[self class] callBackTargetArray]);
		NSLog(@"%@",[[self class] dataArray]);

		NSMutableData *data = [[[self class] dataArray] objectAtIndex:index];
		UIImage *image = [UIImage imageWithData:data];
		[target imageDownloadFinish:image withId:[[[self class] indexArray] objectAtIndex:index]];
		
//		if([target respondsToSelector:selector]) {
//			[target performSelector:selector withObject:data];
//		}
		
		[[[self class] callBackTargetArray] removeObjectAtIndex:index];
		[[[self class] dataArray] removeObjectAtIndex:index];
		[[[self class] indexArray] removeObjectAtIndex:index];
		[connection release];
	}
	
	
	if([[[self class] callBackTargetArray] count] == 0){
		[[[self class] callBackTargetArray] release];
		__callBackTargetArray = nil;
	}
	
	if([[[self class] dataArray] count] == 0){
		[[[self class] dataArray] release];
		__dataArray = nil;
	}
	
	if([[[self class] connectionsArray] count] == 0)
	{
		[[[self class] connectionsArray] release];
		__connectionsArray = nil;
	}
	
}


- (void) configureNetworkReachability: (Reachability*) curReach
{
    NetworkStatus netStatus = [curReach currentReachabilityStatus];
    
	NSString* statusString= @"";
    switch (netStatus)
    {
        case NotReachable:
        {
            statusString = @"Access Not Available";
            
            //Minor interface detail- connectionRequired may return yes, even when the host is unreachable.  We cover that up here...
			[self closeConnection:nil];
            break;
        }
            
        case ReachableViaWWAN:
        {
            statusString = @"Reachable WWAN";
			break;
        }
        case ReachableViaWiFi:
        {
			statusString= @"Reachable WiFi";
            
            break;
		}
    }
    
}

- (void) updateInterfaceWithReachability: (Reachability*) curReach
{
    [self configureNetworkReachability: curReach];
	
}

//Called by Reachability whenever status changes.
- (void) reachabilityChanged: (NSNotification* )note
{
	Reachability* curReach = [note object];
	NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
	[self updateInterfaceWithReachability: curReach];
}


#pragma mark -
#pragma mark Asynchrous NSURLConnection Methods
- (void)connection:(ATConnection *)connection didReceiveData:(NSData *)data {
	
//	NSLog(@"start didReceiveData");
//	NSLog(@"%@",connection);
//	NSLog(@"%@",connection.tag);

	NSInteger index = [[[self class] connectionsArray] indexOfObject:connection];
	[[[[self class] dataArray] objectAtIndex:index] appendData:data];
}

- (void)connection:(ATConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	
//	NSLog(@"start didReceiveResponse");
	if(connection == [[[self class] connectionsArray] objectAtIndex:0])
	{
//		NSLog(@"%@",response);
		
	}
}

- (void)connectionDidFinishLoading:(ATConnection *)connection {
//	NSLog(@"start connectionDidFinishLoading");
	[self closeConnection:connection];
	
}

- (void)connection:(ATConnection *)connection didFailWithError:(NSError *)error {
//	NSLog(@"start didFailWithError");
	[self closeConnection:connection];
}

@end
